// we need to bootstrap main applications here. Page need to provide a context. such as module name here.
define(['jquery', 'mustache', 'module/home/showCommentBox', 'module/home/showUpdateComments',
        'module/template/homeTemplate', 'module/home/fileRenderer' ],
    function($, Mustache, showCommentBox, showUpdateComments, template, fileRenderer ) {
    var update = function(update){

        var typeToMap = {'1' : 'update', '2' : 'info', '3' : 'notice', '4' : 'message', '5' : 'discussion'};

        if(update.user_update_target_type == 'user'){
            var html = $(Mustache.to_html(template['home-message'], update));
            html.find('a.js_remove_update').remove();
            return html;
        }



        // prepare template for update.
        var html = $(Mustache.to_html(template['home-'+typeToMap[update['update_type']]], update));

        var ul = html.find(".list-group");

        // bind fake comment with click event.

        if(update['update_type'] == 1 || update['update_type'] == 5 ){
            showCommentBox(html.find(".fakecomment"), {callback: showUpdateComments, commentDomParent : ul, parentId: update.upid});
        } else {
            html.find('.panel-footer').hide();
        }


        //add delete option on update

        if (update.mine && $.empty(update.resExists)) {
            html.find('a.js_remove_update').click(function () {
                $.ajax({
                    url: '/user/deleteUpdate',
                    method: 'POST',
                    data: {updateId: update.upid}
                }).done(function () {
                    html.remove();
                    // update module factory
                }).fail(function () {
                    alert('oops ..');
                });
            });
        } else {
            html.find('a.js_remove_update').remove();
        }

        if(update.fileUpload && update.fileUpload.file){
            html.find('.panel-body').append(fileRenderer(update.fileUpload.file));
        }

        if(!$.empty(update.comments)()){
            showUpdateComments(update.comments, ul);
        }

        return html;
    };
    return update;
});
